<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <title>文章管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .modal-backdrop {
            z-index: 1040 !important;
        }

        .modal-content {
            z-index: 1050 !important;
        }

        .content-cell {
            max-width: 200px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    </style>
</head>

<body>
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="mb-0">文章管理</h2>
            <div class="d-flex align-items-center gap-2">
                <select class="form-select" id="filterCategorySelect" style="width:180px">
                    <option value="">全部类别</option>
                </select>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addArticleModal">
                    <i class="fa fa-plus me-2"></i>添加文章
                </button>
            </div>
        </div>

        <!-- 文章表格 -->
        <div class="card">
            <div class="card-body">
                <table class="table table-bordered align-middle mb-0" id="articleTable">
                    <thead class="table-light">
                        <tr>
                            <th style="width:60px;">#</th>
                            <th>标题</th>
                            <th>类别</th>
                            <th style="width:100px;">作者ID</th>
                            <th style="width:80px;">状态</th>
                            <th style="width:150px;">发布时间</th>
                            <th style="width:180px;">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- JS填充 -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 添加文章模态框 -->
        <div class="modal fade" id="addArticleModal" tabindex="-1" aria-labelledby="addArticleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addArticleModalLabel">添加文章</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">标题</label>
                            <input type="text" class="form-control" id="articleTitleInput" placeholder="请输入标题">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">内容</label>
                            <textarea class="form-control" id="articleContentInput" rows="3"
                                placeholder="请输入内容"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">类别</label>
                            <select class="form-select" id="articleCategorySelect">
                                <option value="">请选择类别</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="addArticleBtn">添加</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改文章状态模态框，放在所有script标签之前 -->
    <div class="modal fade" id="editStatusModal" tabindex="-1" aria-labelledby="editStatusModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editStatusModalLabel">修改文章状态</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="editStatusArticleId">
                    <div class="mb-3">
                        <label class="form-label">请选择状态</label>
                        <select class="form-select" id="editStatusSelect">
                            <option value="1">已发布</option>
                            <option value="0">已禁用</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveStatusBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="/jquery-3.7.1.min.js"></script>
    <script>
        // 文章数据（前端模拟）
        let articles = []; // 文章数据，从后端获取
        // 类别数据
        let categories = [];

        // 渲染文章表格，支持筛选
        function renderArticleTable() {
            const tbody = $('#articleTable tbody');
            tbody.empty();
            const filterCategoryName = $('#filterCategorySelect').val();
            let filteredArticles = articles;
            if (filterCategoryName) {
                // 找到选中的类别的ID
                const selectedCategory = categories.find(cat => cat.name === filterCategoryName);
                if (selectedCategory) {
                    filteredArticles = articles.filter(art => art.tagId === selectedCategory.id);
                } else {
                    filteredArticles = []; // 如果找不到类别，显示空列表
                }
            }
            filteredArticles.forEach((art, idx) => {
                const statusBtn = art.status === 1
                    ? '<button class="btn btn-success btn-sm" disabled>已发布</button>'
                    : '<button class="btn btn-secondary btn-sm" disabled>已禁用</button>';
                const tr = $(
                    `<tr>
                        <td>${art.id}</td>
                        <td>${art.title}</td>
                        <td>${categories.find(cat => cat.id === art.tagId)?.name || '未知类别'}</td>
                        <td>${art.authorId || '无'}</td>
                        <td>${statusBtn}</td>
                        <td>${art.createdAt || '无'}</td>
                        <td>
                            <div class="d-flex gap-1">
                                <button class="btn btn-sm btn-info detail-btn" data-id="${art.id}" style="white-space: nowrap;"><i class="fa fa-info-circle"></i> 详情</button>
                                <button class="btn btn-sm btn-warning edit-btn" data-id="${art.id}" data-status="${art.status}" style="white-space: nowrap;"><i class="fa fa-pencil"></i> 编辑</button>
                                <button class="btn btn-sm btn-danger delete-btn" data-id="${art.id}" style="white-space: nowrap;"><i class="fa fa-trash"></i> 删除</button>
                            </div>
                        </td>
                    </tr>`
                );
                tr.find('.delete-btn').click(function () {
                    if (confirm('确定要删除该文章吗？')) {
                        // 调用后端接口删除文章
                        $.ajax({
                            url: `http://localhost:8082/api/articles/${art.id}`, // 你的文章删除接口，假设是 DELETE /{id}
                            method: 'DELETE',
                            dataType: 'json',
                            success: function (data) {
                                if (data.code === 200) {
                                    alert('删除成功！');
                                    fetchArticles(); // 刷新文章列表
                                } else {
                                    console.error('删除失败:', data.msg);
                                    alert('删除失败：' + (data.msg || '未知错误'));
                                }
                            },
                            error: function (xhr, status, error) {
                                console.error('删除请求失败:', status, error, xhr.responseText);
                                alert('删除失败，无法连接到服务器');
                            }
                        });
                    }
                });

                // 详情按钮点击事件，跳转到详情页
                tr.find('.detail-btn').click(function () {
                    const articleId = $(this).data('id');
                    window.location.href = '/hou/articles/article_detail.html?articleId=' + articleId;
                });

                // 编辑按钮点击事件，弹出状态修改模态框
                tr.find('.edit-btn').click(function () {
                    const articleId = $(this).data('id');
                    const status = $(this).data('status');
                    $('#editStatusArticleId').val(articleId);
                    $('#editStatusSelect').val(String(status));
                    const modal = new bootstrap.Modal(document.getElementById('editStatusModal'));
                    modal.show();
                });

                tbody.append(tr);
            });
        }

        // 渲染类别下拉（用于添加和筛选）
        function renderCategorySelect() {
            const select = $('#articleCategorySelect');
            select.empty();
            select.append('<option value="">请选择类别</option>');
            categories.forEach(cat => {
                select.append(`<option value="${cat.name}">${cat.name}</option>`);
            });
            // 渲染筛选下拉
            const filterSelect = $('#filterCategorySelect');
            const currentFilterName = filterSelect.val();
            filterSelect.empty();
            filterSelect.append('<option value="">全部类别</option>');
            categories.forEach(cat => {
                filterSelect.append(`<option value="${cat.name}">${cat.name}</option>`);
            });
            filterSelect.val(currentFilterName || '');
        }

        // 获取类别列表
        function fetchCategories() {
            $.ajax({
                url: 'http://localhost:8082/api/tags/',
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    if (data.code === 200 && Array.isArray(data.data)) {
                        categories = data.data;
                        renderCategorySelect();
                    }
                }
            });
            // 返回 $.ajax 对象，以便链式调用 .done()
            return $.ajax({
                url: 'http://localhost:8082/api/tags/', // 你的后端类别接口
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    if (data.code === 200 && Array.isArray(data.data)) {
                        categories = data.data;
                        renderCategorySelect();
                    } else {
                        console.error('获取类别列表失败:', data.msg);
                        alert('获取类别列表失败: ' + (data.msg || '未知错误'));
                    }
                },
                error: function (xhr, status, error) {
                    console.error('获取类别列表失败:', status, error, xhr.responseText);
                    alert('获取类别列表失败，无法连接到服务器');
                }
            });
        }

        // 获取文章列表
        function fetchArticles() {
            $.ajax({
                url: 'http://localhost:8082/api/articles/', // 你的后端文章列表接口
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    if (data.code === 200 && Array.isArray(data.data)) {
                        articles = data.data;
                        renderArticleTable();
                    } else {
                        console.error('获取文章列表失败:', data.msg);
                        alert('获取文章列表失败: ' + (data.msg || '未知错误'));
                    }
                },
                error: function (xhr, status, error) {
                    console.error('获取文章列表失败:', status, error, xhr.responseText);
                    alert('获取文章列表失败，无法连接到服务器');
                }
            });
        }

        // 添加文章
        $('#addArticleBtn').click(function () {
            const title = $('#articleTitleInput').val().trim();
            const content = $('#articleContentInput').val().trim();
            const categoryName = $('#articleCategorySelect').val();
            if (!title) {
                alert('请输入标题');
                return;
            }
            if (!content) {
                alert('请输入内容');
                return;
            }
            if (!categoryName) {
                alert('请选择类别');
                return;
            }

            // 查找选中的类别的ID（如果后端需要ID的话）
            const selectedCategory = categories.find(cat => cat.name === categoryName);
            const categoryId = selectedCategory ? selectedCategory.id : null; // 假设类别对象有 id 字段

            // 构造文章数据对象，根据你的后端接口需要调整
            // 我假设后端期望接收一个包含 title, content, categoryName (或 categoryId) 的 JSON 对象
            const articleData = {
                title: title,
                content: content,
                // 根据后端接口的需求，可能发送 categoryName 或 
                tagId: categoryId,
                authorId: sessionStorage.getItem('userId'),
                // categoryName: categoryName // 这里先发送类别名称
                // 如果后端需要类别ID，请使用 categoryId: categoryId
                // 可能还需要其他字段，如作者ID等
            };
            console.log('articleData:', articleData);

            // 调用后端接口保存文章
            $.ajax({
                url: 'http://localhost:8082/api/articles/add', // 你的文章保存接口
                method: 'POST',
                contentType: 'application/json', // 指明发送的数据是 JSON 格式
                data: JSON.stringify(articleData), // 将数据对象转换为 JSON 字符串
                // dataType: 'json', // 期望后端返回的数据格式
                success: function (data) {
                    if (data.code === 200) {
                        alert('文章保存成功！');
                        // 清空表单并关闭模态框
                        $('#articleTitleInput').val('');
                        $('#articleContentInput').val('');
                        $('#articleCategorySelect').val('');
                        const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('addArticleModal'));
                        modal.hide();
                        // 刷新文章列表
                        fetchArticles();
                    } else {
                        console.error('文章保存失败:', data.msg);
                        alert('文章保存失败：' + (data.msg || '未知错误'));
                    }
                },
                error: function (xhr, status, error) {
                    console.error('文章保存失败:', status, error, xhr.responseText);
                    alert('文章保存失败，无法连接到服务器或服务器返回错误');
                }
            });
        });

        // 筛选下拉事件
        $('#filterCategorySelect').on('change', function () {
            renderArticleTable(); // 根据选中的类别重新渲染表格
        });

        // 保存状态按钮点击事件
        $('#saveStatusBtn').off('click').on('click', function () {
            const articleId = $('#editStatusArticleId').val();
            const status = $('#editStatusSelect').val();
            console.log('即将提交:', articleId, status); // 调试用
            $.ajax({
                url: `http://localhost:8082/api/articles/status/${articleId}`,
                method: 'PUT',
                data: { status: status },
                success: function (data) {
                    if (data.code === 200) {
                        alert('状态更新成功！');
                        const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('editStatusModal'));
                        modal.hide();
                        fetchArticles();
                    } else {
                        alert('状态更新失败：' + (data.msg || '未知错误'));
                    }
                },
                error: function (xhr, status, error) {
                    alert('状态更新失败，无法连接到服务器');
                }
            });
        });

        // 初始化
        $(function () {
            fetchCategories(); // 获取类别用于筛选
            // 获取类别后再获取文章，确保渲染时可以找到类别名称
            fetchCategories().done(function () {
                fetchArticles();
            });
        });
    </script>
</body>

</html>